/**
 * A dialog to delete ItemClasses 
 * @author lemmar@lu.unisi.ch &  zulianp@lu.unisi.ch
 */

package ch.unisi.inf.projects.java.uom.gui.itemclasseditor;

import java.util.Set;
import java.util.HashSet;
import javax.swing.JDialog;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.FlowLayout;

import ch.unisi.inf.projects.java.uom.gui.UOMImages;
import ch.unisi.inf.projects.java.uom.gui.commands.IconedCommand;
import ch.unisi.inf.projects.java.uom.elements.ItemManager;
import ch.unisi.inf.projects.java.uom.elements.ItemClass;
import ch.unisi.inf.projects.java.uom.gui.UOMMainFrame;

public final class UOMItemClassDeleterDialog extends JDialog
{
    /** We are not going to serialize this class atm */
    private static final long serialVersionUID = -1L;
    
	public UOMItemClassDeleterDialog ()
	{
		super();
		this.setTitle("Delete a Category");
		this.setLayout(new BorderLayout());
		this.setMinimumSize(new Dimension(300,100));
		this.setMaximumSize(this.getMinimumSize());
		this.setResizable(false);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		UOMMainFrame.instance().setEnabled(false);
		this.addWindowListener(new WindowAdapter() {
			public void windowClosed (final WindowEvent ev) { UOMMainFrame.instance().setEnabled(true); }
		});
		makeDialog();
		this.setLocationRelativeTo(null);
		this.setVisible(true);
	}
	
	private void makeDialog ()
	{
		Set<ItemClass> itemClasses; 
		try {
			itemClasses = ItemManager.instance().getItemClasses();
		}
		catch (Exception e) {
			itemClasses = new HashSet<ItemClass>();
		}
		this.add(new JLabel("Choose a category to be deleted:"), BorderLayout.NORTH);
		final JComboBox chooser = new JComboBox(itemClasses.toArray());
		this.add(chooser, BorderLayout.CENTER);
		final JPanel buttonPanel = new JPanel(new FlowLayout());
		final JButton delete = new JButton(new IconedCommand ("", "Deletes the selected ItemClass", UOMImages.OK.getFileName()) {
		    private static final long serialVersionUID = -1L;
			public void actionPerformed (final ActionEvent ev) {
				final ItemClass itemClass = (ItemClass) chooser.getSelectedItem();
				try {
					ItemManager.instance().elementDelete(itemClass);
				}
				catch (final Exception e)
				{
					UOMMainFrame.instance().setEnabled(true);
					dispose();
				}
				UOMMainFrame.instance().setEnabled(true);
				dispose();
			}
		} );
		final JButton cancel = new JButton (new IconedCommand ("", "Cancel and close the window", UOMImages.CANCEL.getFileName()) { 
		    private static final long serialVersionUID = -1L;
			public void actionPerformed (final ActionEvent ev) {
				dispose();
			}
		});
		buttonPanel.add(delete);
		buttonPanel.add(cancel);
		this.add(buttonPanel, BorderLayout.SOUTH);
		this.pack();
	}

}
